<template>
  <div class="echart-container" ref="echart"></div>
</template>

<script>
export default {
  props: {
    echartObj: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },

  mounted() {
    this.myChart = this.$echarts.init(this.$refs.echart);
    this.$watch(
      "echartObj",
      () => {
        this.initChart();
      },
      {
        deep: true
      }
    );
  },

  methods: {
    initChart() {
      // 指定图表的配置项和数据

      let seriesArr = [];
      // console.log(this.echartObj.data, "echartObj.series");
      let colorArr = this.echartObj.color || ["#58EEF2", "#63ACFF", "#AF81FF"];
      this.echartObj.series.forEach((item, index) => {
        if (item) {
          seriesArr.push({
            name: item.name || "",
            type: item.type,
            data: item.data || [30, 20, 28, 19, 24],
            barWidth: 16,
            itemStyle: {
              color: colorArr[index] || "#FFBA22" //this.echartObj.color[index] || "#FFBA22",
            },
            label: {
              show: item.type == "bar" ? true : false,
              position: "top",
              formatter: "{c}", // 显示柱子对应的数据值
              textStyle: {
                color: "#949BA4", // 修改字体颜色为红色
                fontSize: 12 // 修改字体大小为12px
              }
            }
          });
        }
      });
      let option = {
        title: {
          text: this.echartObj.title && this.echartObj.title,
          textStyle: {
            fontSize: 16,
            fontWeight: "bold",
            color: "#FFFFFF"
          },
          left: 'center' // 设置标题居中
        },
        tooltip: {
          trigger: "axis"
        },

        legend: {
          textStyle: {
            fontSize: 16, //字体大小
            color: "#949BA4" //字体颜色
          },
          data: this.echartObj.data.filter(item => item),
          bottom: this.echartObj.bottom && this.echartObj.bottom
        },

        xAxis: {
          data: this.echartObj.xAxis
        },

        yAxis: {
          name: `单位：${this.echartObj.unit}`
        },
        series: seriesArr
      };
      // 使用刚指定的配置项和数据显示图表。
      this.myChart.setOption(option);
    }
  }
};
</script>

<style lang="scss" scoped>
.echart-container {
  width: 100%;
  height: 100%;
}
</style>